package com.sdms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Paths;
import javax.annotation.Resource;

import static com.sdms.common.util.StringUtils.isBlankOrNull;

@SuppressWarnings("unused")
@Configuration
public class MvcConfig {

    private static final Logger log = LoggerFactory.getLogger(MvcConfig.class);

    @Resource
    private PictureConfig pictureConfig;

    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                // 静态资源路径映射
                String path = pictureConfig.getPath();
                if (isBlankOrNull(path)) {
                    String userDir = System.getProperty("user.dir");
                    log.info("user.dir={}", userDir);
                    if (isBlankOrNull(userDir)) {
                        throw new IllegalStateException("System property 'user.dir' is not available");
                    }
                    path = Paths.get(userDir, "picture-path").normalize().toAbsolutePath().toString().replace("\\", "/");
                }
                if (!path.endsWith("/")) {
                    path = path + "/";
                }
                log.info("Mapping /sdms-images/** to local path: {}", path);
                // 将 http://localhost:8080/sdms-images/** 格式的 URL映射到 path 这个本地绝对路径下
                registry.addResourceHandler("/sdms-images/**").addResourceLocations("file:" + path);
            }
        };
    }
}
